/**
 * 新的配置管理器
 * 替代复杂的Excel转JSON系统，提供类型安全和更好的开发体验
 */

import { 
    EquipmentTemplate, 
    SkillConfig, 
    ConfigValidationResult, 
    EnchantCondition,
    SkillTreeConfig,
    SkillUpgradeConfig,
    SkillSystemConfig,
    AdvancedSkillEffectConfig 
} from './types/ConfigTypes';

/**
 * 配置管理器类
 */
export class ConfigManager {
    // === 装备配置管理 ===
    private equipmentTemplates = new Map<string, EquipmentTemplate>();
    private equipmentsByJob = new Map<string, EquipmentTemplate[]>();
    private equipmentsBySysType = new Map<string, EquipmentTemplate[]>();
    
    // === 技能配置管理 ===
    private skillConfigs = new Map<string, SkillConfig>();
    private skillTreeConfigs = new Map<string, SkillTreeConfig>();
    private skillUpgradeConfigs = new Map<string, SkillUpgradeConfig>();
    private skillEffectConfigs = new Map<string, AdvancedSkillEffectConfig>();
    private skillsByCategory = new Map<string, SkillConfig[]>();
    private skillsByType = new Map<string, SkillConfig[]>();
    
    private isInitialized = false;
    
    /**
     * 初始化配置管理器
     */
    async initialize(): Promise<void> {
        if (this.isInitialized) {
            console.warn('ConfigManager already initialized');
            return;
        }
        
        try {
            console.log('🔧 Loading equipment configurations...');
            await this.loadEquipmentConfigs();
            
            console.log('🎯 Loading skill configurations...');
            await this.loadSkillConfigs();
            
            console.log('✅ Building configuration indexes...');
            this.buildIndexes();
            
            console.log('🔍 Validating configurations...');
            const validation = this.validateAllConfigs();
            
            if (!validation.isValid) {
                console.error('❌ Configuration validation failed:', validation.errors);
                throw new Error('Invalid configurations detected');
            }
            
            if (validation.warnings.length > 0) {
                console.warn('⚠️ Configuration warnings:', validation.warnings);
            }
            
            this.isInitialized = true;
            console.log(`✅ ConfigManager initialized successfully`);
            console.log(`📊 Loaded ${this.equipmentTemplates.size} equipment templates`);
            console.log(`🎯 Loaded ${this.skillConfigs.size} skill configurations`);
            console.log(`🌳 Loaded ${this.skillTreeConfigs.size} skill trees`);
            
        } catch (error) {
            console.error('❌ Failed to initialize ConfigManager:', error);
            throw error;
        }
    }
    
    /**
     * 加载装备配置
     */
    private async loadEquipmentConfigs(): Promise<void> {
        // 动态导入所有装备配置文件
        // 这比Excel转JSON更灵活，支持代码分割和按需加载
        const configModules = await Promise.all([
            import('./equipment/BloodKnightEquipments'),
            import('./equipment/ShadowAssassinEquipments'),
            import('./equipment/HolyPriestEquipments'),
            // 可以轻松添加更多配置文件
            // import('./equipment/FireMageEquipments'),
            // import('./equipment/IceWarriorEquipments'),
        ]);
        
        // 合并所有配置
        for (const module of configModules) {
            // 获取模块中的所有导出配置
            const collections = Object.values(module).filter(
                value => value && typeof value === 'object' && 'data' in value
            );
            
            for (const collection of collections) {
                const data = (collection as any).data;
                if (Array.isArray(data)) {
                    for (const template of data) {
                        if (this.isValidEquipmentTemplate(template)) {
                            this.equipmentTemplates.set(template.id, template);
                        } else {
                            console.warn(`Invalid equipment template: ${template.id}`);
                        }
                    }
                }
            }
        }
    }
    
    /**
     * 加载技能配置
     */
    private async loadSkillConfigs(): Promise<void> {
        // 这里可以扩展支持动态导入技能配置文件
        // 目前先提供基础框架，等待具体的技能配置文件创建
        
        try {
            // TODO: 当有具体的技能配置文件时，可以按以下模式动态导入
            // const skillModules = await Promise.all([
            //     import('./skills/BloodKnightSkills'),
            //     import('./skills/HolyPriestSkills'),
            //     import('./skills/ShadowAssassinSkills'),
            // ]);
            
            // 现在先从装备模板中提取技能配置作为示例
            this.extractSkillsFromEquipments();
            
            console.log(`✅ Extracted ${this.skillConfigs.size} skills from equipment templates`);
            
        } catch (error) {
            console.warn('⚠️ Failed to load skill configurations:', error);
            // 技能配置加载失败不应该阻止整个系统启动
        }
    }
    
    /**
     * 从装备模板中提取技能配置（作为技能配置的数据源）
     */
    private extractSkillsFromEquipments(): void {
        for (const equipment of Array.from(this.equipmentTemplates.values())) {
            // 提取固有技能
            if (equipment.skillPools.inherent) {
                for (const skill of equipment.skillPools.inherent) {
                    if (skill.skillId && !this.skillConfigs.has(skill.skillId)) {
                        // 补充缺失的字段，确保与现代技能系统兼容
                        const enhancedSkill: SkillConfig = {
                            ...skill,
                            name: skill.reName || skill.name || skill.skillId,
                            description: skill.desc || skill.description || '',
                            category: skill.category || skill.classType || 'equipment',
                            effects: skill.effects || skill.effect || [],
                            tags: skill.tags || ['equipment', 'inherent'],
                            quality: skill.quality || 2,
                            cooldown: skill.cooldown || 0,
                        };
                        this.skillConfigs.set(skill.skillId, enhancedSkill);
                    }
                }
            }
            
            // 提取可附魔技能
            if (equipment.skillPools.enchantable) {
                for (const pool of equipment.skillPools.enchantable) {
                    const skill = pool.skill;
                    if (skill.skillId && !this.skillConfigs.has(skill.skillId)) {
                        const enhancedSkill: SkillConfig = {
                            ...skill,
                            name: skill.reName || skill.name || skill.skillId,
                            description: skill.desc || skill.description || '',
                            category: skill.category || skill.classType || 'equipment',
                            effects: skill.effects || skill.effect || [],
                            tags: skill.tags || ['equipment', 'enchantable'],
                            quality: skill.quality || 2,
                            cooldown: skill.cooldown || 0,
                        };
                        this.skillConfigs.set(skill.skillId, enhancedSkill);
                    }
                }
            }
            
            // 提取专属技能
            if (equipment.skillPools.exclusive) {
                for (const exclusive of equipment.skillPools.exclusive) {
                    const skill = exclusive.skill;
                    if (skill.skillId && !this.skillConfigs.has(skill.skillId)) {
                        const enhancedSkill: SkillConfig = {
                            ...skill,
                            name: skill.reName || skill.name || skill.skillId,
                            description: skill.desc || skill.description || '',
                            category: skill.category || skill.classType || 'equipment',
                            effects: skill.effects || skill.effect || [],
                            tags: skill.tags || ['equipment', 'exclusive'],
                            quality: skill.quality || 3, // 专属技能通常品质更高
                            cooldown: skill.cooldown || 0,
                        };
                        this.skillConfigs.set(skill.skillId, enhancedSkill);
                    }
                }
            }
        }
    }
    
    /**
     * 构建索引以提高查询性能
     */
    private buildIndexes(): void {
        // === 装备索引构建 ===
        this.equipmentsByJob.clear();
        this.equipmentsBySysType.clear();
        
        for (const template of Array.from(this.equipmentTemplates.values())) {
            // 按职业索引
            const jobKey = template.job;
            if (!this.equipmentsByJob.has(jobKey)) {
                this.equipmentsByJob.set(jobKey, []);
            }
            this.equipmentsByJob.get(jobKey)!.push(template);
            
            // 按体系-类型索引
            const sysTypeKey = `${template.sys}-${template.type}`;
            if (!this.equipmentsBySysType.has(sysTypeKey)) {
                this.equipmentsBySysType.set(sysTypeKey, []);
            }
            this.equipmentsBySysType.get(sysTypeKey)!.push(template);
        }
        
        // === 技能索引构建 ===
        this.skillsByCategory.clear();
        this.skillsByType.clear();
        
        for (const skill of Array.from(this.skillConfigs.values())) {
            // 按分类索引
            const category = skill.category || skill.classType || 'unknown';
            if (!this.skillsByCategory.has(category)) {
                this.skillsByCategory.set(category, []);
            }
            this.skillsByCategory.get(category)!.push(skill);
            
            // 按类型索引
            const type = skill.type || 'unknown';
            if (!this.skillsByType.has(type)) {
                this.skillsByType.set(type, []);
            }
            this.skillsByType.get(type)!.push(skill);
        }
        
        console.log(`📋 Built indexes: ${this.equipmentsByJob.size} job groups, ${this.skillsByCategory.size} skill categories`);
    }
    
    /**
     * 验证装备模板格式
     */
    private isValidEquipmentTemplate(template: any): template is EquipmentTemplate {
        return template &&
               typeof template.id === 'string' &&
               typeof template.name === 'string' &&
               typeof template.sys === 'string' &&
               typeof template.type === 'string' &&
               typeof template.job === 'string' &&
               typeof template.solt === 'string' &&
               template.skillPools &&
               Array.isArray(template.skillPools.inherent) &&
               Array.isArray(template.skillPools.enchantable);
    }
    
    /**
     * 验证所有配置
     */
    private validateAllConfigs(): ConfigValidationResult {
        const errors: string[] = [];
        const warnings: string[] = [];
        let validatedCount = 0;
        
        for (const [id, template] of Array.from(this.equipmentTemplates)) {
            try {
                // 验证基础字段
                if (!template.name || template.name.trim() === '') {
                    errors.push(`Equipment ${id}: name is empty`);
                }
                
                // 验证技能配置
                const skillValidation = this.validateSkillPools(template.skillPools);
                errors.push(...skillValidation.errors.map(err => `Equipment ${id}: ${err}`));
                warnings.push(...skillValidation.warnings.map(warn => `Equipment ${id}: ${warn}`));
                
                // 验证属性配置
                for (const attr of template.baseAttributes) {
                    if (attr.min > attr.max) {
                        errors.push(`Equipment ${id}: attribute ${attr.key} min > max`);
                    }
                    
                    // 验证属性值的合理性
                    if (attr.min < 0 || attr.max < 0) {
                        errors.push(`Equipment ${id}: attribute ${attr.key} has negative values`);
                    }
                    
                    // 验证增长类型
                    if (attr.growthType && !['linear', 'exponential', 'logarithmic'].includes(attr.growthType)) {
                        errors.push(`Equipment ${id}: attribute ${attr.key} has invalid growthType: ${attr.growthType}`);
                    }
                    
                    // 验证品质乘数
                    if (attr.qualityMultiplier && (attr.qualityMultiplier <= 0 || attr.qualityMultiplier > 3)) {
                        warnings.push(`Equipment ${id}: attribute ${attr.key} has unusual qualityMultiplier: ${attr.qualityMultiplier}`);
                    }
                }
                
                // 验证品质配置
                if (template.quality.weights && Array.isArray(template.quality.weights)) {
                    const totalWeight = template.quality.weights.reduce((sum, weight) => sum + weight, 0);
                    if (totalWeight === 0) {
                        warnings.push(`Equipment ${id}: total quality weights is 0`);
                    }
                    
                    // 验证权重数组长度与品质范围匹配
                    const expectedLength = template.quality.max - template.quality.min + 1;
                    if (template.quality.weights.length !== expectedLength) {
                        errors.push(`Equipment ${id}: quality weights length (${template.quality.weights.length}) doesn't match quality range (${expectedLength})`);
                    }
                }
                
                validatedCount++;
            } catch (error) {
                errors.push(`Equipment ${id}: validation error - ${(error as any).message}`);
            }
        }
        
        return {
            isValid: errors.length === 0,
            errors,
            warnings,
            validatedCount
        };
    }
    
    /**
     * 验证技能池配置
     */
    private validateSkillPools(skillPools: any): { errors: string[], warnings: string[] } {
        const errors: string[] = [];
        const warnings: string[] = [];
        
        // 验证固有技能
        if (!Array.isArray(skillPools.inherent)) {
            errors.push('inherent skills must be an array');
        } else {
            for (const skill of skillPools.inherent) {
                if (!skill.skillId) {
                    errors.push('inherent skill missing skillId');
                }
            }
        }
        
        // 验证可附魔技能
        if (!Array.isArray(skillPools.enchantable)) {
            errors.push('enchantable skills must be an array');
        } else {
            let totalWeight = 0;
            for (const pool of skillPools.enchantable) {
                if (!pool.skill || !pool.skill.skillId) {
                    errors.push('enchantable skill missing skillId');
                }
                if (typeof pool.weight !== 'number' || pool.weight <= 0) {
                    errors.push('enchantable skill weight must be positive number');
                }
                
                // 验证技能配置的完整性
                if (pool.skill) {
                    if (!pool.skill.reName && !pool.skill.desc) {
                        warnings.push('enchantable skill missing both reName and desc');
                    }
                    
                    if (pool.skill.maxLevel && (pool.skill.maxLevel < 1 || pool.skill.maxLevel > 20)) {
                        warnings.push(`enchantable skill maxLevel (${pool.skill.maxLevel}) is outside reasonable range`);
                    }
                }
                
                // 验证条件配置
                if (pool.conditions) {
                    if (pool.conditions.minLevel && (pool.conditions.minLevel < 1 || pool.conditions.minLevel > 100)) {
                        warnings.push(`enchantable skill minLevel (${pool.conditions.minLevel}) is outside reasonable range`);
                    }
                }
                
                // 验证最大数量限制
                if (pool.maxCount && (pool.maxCount < 1 || pool.maxCount > 10)) {
                    warnings.push(`enchantable skill maxCount (${pool.maxCount}) is outside reasonable range`);
                }
                
                totalWeight += pool.weight;
            }
            
            if (totalWeight === 0) {
                warnings.push('total enchantable skill weight is 0');
            }
        }
        
        return { errors, warnings };
    }
    
    // ==================== 公共查询方法 ====================
    
    /**
     * 获取装备模板
     */
    getEquipmentTemplate(id: string): EquipmentTemplate | undefined {
        this.ensureInitialized();
        return this.equipmentTemplates.get(id);
    }
    
    /**
     * 获取指定职业的所有装备
     */
    getEquipmentsByJob(job: string): EquipmentTemplate[] {
        this.ensureInitialized();
        return this.equipmentsByJob.get(job) || [];
    }
    
    /**
     * 获取指定体系和类型的装备
     */
    getEquipmentsBySysType(sys: string, type: string): EquipmentTemplate[] {
        this.ensureInitialized();
        const key = `${sys}-${type}`;
        return this.equipmentsBySysType.get(key) || [];
    }
    
    /**
     * 获取可附魔技能列表（新的简化实现）
     * 替代原来复杂的EquipService.getEnchantableSkills方法
     */
    getEnchantableSkills(sys: string, type: string, job: string, solt: string, playerLevel: number = 1): SkillConfig[] {
        this.ensureInitialized();
        
        // 查找匹配的装备模板
        const template = Array.from(this.equipmentTemplates.values()).find(tmpl =>
            tmpl.sys === sys &&
            tmpl.type === type &&
            tmpl.job === job &&
            tmpl.solt === solt
        );
        
        if (!template) {
            console.warn(`No equipment template found for ${sys}-${type}-${job}-${solt}`);
            return [];
        }
        
        // 过滤符合条件的技能
        return template.skillPools.enchantable
            .filter(pool => this.checkEnchantConditions(pool.conditions, playerLevel))
            .map(pool => pool.skill);
    }
    
    /**
     * 检查附魔条件
     */
    private checkEnchantConditions(conditions?: EnchantCondition, playerLevel: number = 1): boolean {
        if (!conditions) return true;
        
        // 检查等级要求
        if (conditions.minLevel && playerLevel < conditions.minLevel) {
            return false;
        }
        
        // 检查血统要求
        if (conditions.requiredTalent) {
            // TODO: 实现血统检查逻辑
            // const hasTalent = this.checkPlayerTalent(playerId, conditions.requiredTalent);
            // if (!hasTalent) return false;
        }
        
        // 检查任务要求
        if (conditions.requiredQuest) {
            // TODO: 实现任务完成检查
            // const questCompleted = this.checkQuestCompletion(playerId, conditions.requiredQuest);
            // if (!questCompleted) return false;
        }
        
        return true;
    }
    
    /**
     * 随机选择附魔技能
     */
    selectRandomEnchantSkill(sys: string, type: string, job: string, solt: string, playerLevel: number = 1): SkillConfig | null {
        const template = Array.from(this.equipmentTemplates.values()).find(tmpl =>
            tmpl.sys === sys && tmpl.type === type && tmpl.job === job && tmpl.solt === solt
        );
        
        if (!template) return null;
        
        // 获取符合条件的技能池
        const availablePools = template.skillPools.enchantable
            .filter(pool => this.checkEnchantConditions(pool.conditions, playerLevel));
        
        if (availablePools.length === 0) return null;
        
        // 按权重随机选择
        const totalWeight = availablePools.reduce((sum, pool) => sum + pool.weight, 0);
        let random = Math.random() * totalWeight;
        
        for (const pool of availablePools) {
            random -= pool.weight;
            if (random <= 0) {
                return pool.skill;
            }
        }
        
        // fallback
        return availablePools[0].skill;
    }
    
    /**
     * 获取装备的固有技能
     */
    getInherentSkills(equipmentId: string): SkillConfig[] {
        const template = this.getEquipmentTemplate(equipmentId);
        return template ? template.skillPools.inherent : [];
    }
    
    /**
     * 获取所有装备模板
     */
    getAllEquipmentTemplates(): EquipmentTemplate[] {
        this.ensureInitialized();
        return Array.from(this.equipmentTemplates.values());
    }
    
    /**
     * 获取统计信息
     */
    getStats(): {
        totalEquipments: number;
        equipmentsByJob: Record<string, number>;
        equipmentsBySys: Record<string, number>;
        equipmentsByType: Record<string, number>;
        qualityDistribution: Record<string, number>;
    } {
        this.ensureInitialized();
        
        const equipmentsByJob: Record<string, number> = {};
        const equipmentsBySys: Record<string, number> = {};
        const equipmentsByType: Record<string, number> = {};
        const qualityDistribution: Record<string, number> = {};
        
        for (const template of Array.from(this.equipmentTemplates.values())) {
            // 按职业统计
            equipmentsByJob[template.job] = (equipmentsByJob[template.job] || 0) + 1;
            
            // 按体系统计
            equipmentsBySys[template.sys] = (equipmentsBySys[template.sys] || 0) + 1;
            
            // 按类型统计
            equipmentsByType[template.type] = (equipmentsByType[template.type] || 0) + 1;
            
            // 按品质范围统计
            const qualityKey = `${template.quality.min}-${template.quality.max}`;
            qualityDistribution[qualityKey] = (qualityDistribution[qualityKey] || 0) + 1;
        }
        
        return {
            totalEquipments: this.equipmentTemplates.size,
            equipmentsByJob,
            equipmentsBySys,
            equipmentsByType,
            qualityDistribution
        };
    }
    
    // ==================== 技能配置查询方法 ====================
    
    /**
     * 获取技能配置
     */
    getSkillConfig(skillId: string): SkillConfig | undefined {
        this.ensureInitialized();
        return this.skillConfigs.get(skillId);
    }
    
    /**
     * 获取指定分类的所有技能
     */
    getSkillsByCategory(category: string): SkillConfig[] {
        this.ensureInitialized();
        return this.skillsByCategory.get(category) || [];
    }
    
    /**
     * 获取指定类型的所有技能
     */
    getSkillsByType(type: string): SkillConfig[] {
        this.ensureInitialized();
        return this.skillsByType.get(type) || [];
    }
    
    /**
     * 搜索技能
     */
    searchSkills(criteria: {
        name?: string;
        category?: string;
        type?: string;
        quality?: number;
        tags?: string[];
        minLevel?: number;
        maxLevel?: number;
    }): SkillConfig[] {
        this.ensureInitialized();
        
        let results = Array.from(this.skillConfigs.values());
        
        // 按名称过滤
        if (criteria.name) {
            const searchName = criteria.name.toLowerCase();
            results = results.filter(skill => 
                (skill.name && skill.name.toLowerCase().includes(searchName)) ||
                (skill.reName && skill.reName.toLowerCase().includes(searchName)) ||
                skill.skillId.toLowerCase().includes(searchName)
            );
        }
        
        // 按分类过滤
        if (criteria.category) {
            results = results.filter(skill => 
                skill.category === criteria.category || skill.classType === criteria.category
            );
        }
        
        // 按类型过滤
        if (criteria.type) {
            results = results.filter(skill => skill.type === criteria.type);
        }
        
        // 按品质过滤
        if (criteria.quality !== undefined) {
            results = results.filter(skill => skill.quality === criteria.quality);
        }
        
        // 按标签过滤
        if (criteria.tags && criteria.tags.length > 0) {
            results = results.filter(skill => 
                skill.tags && criteria.tags!.some(tag => skill.tags!.includes(tag))
            );
        }
        
        // 按等级范围过滤
        if (criteria.minLevel !== undefined) {
            results = results.filter(skill => 
                skill.level !== undefined && skill.level >= criteria.minLevel!
            );
        }
        
        if (criteria.maxLevel !== undefined) {
            results = results.filter(skill => 
                skill.maxLevel !== undefined && skill.maxLevel <= criteria.maxLevel!
            );
        }
        
        return results;
    }
    
    /**
     * 获取技能树配置
     */
    getSkillTree(treeId: string): SkillTreeConfig | undefined {
        this.ensureInitialized();
        return this.skillTreeConfigs.get(treeId);
    }
    
    /**
     * 获取所有技能树
     */
    getAllSkillTrees(): SkillTreeConfig[] {
        this.ensureInitialized();
        return Array.from(this.skillTreeConfigs.values());
    }
    
    /**
     * 获取技能升级配置
     */
    getSkillUpgradeConfig(skillId: string): SkillUpgradeConfig | undefined {
        this.ensureInitialized();
        return this.skillUpgradeConfigs.get(skillId);
    }
    
    /**
     * 验证技能配置兼容性
     * 检查技能配置是否与现代技能系统兼容
     */
    validateSkillCompatibility(skillId: string): {
        isCompatible: boolean;
        issues: string[];
        suggestions: string[];
    } {
        const skill = this.getSkillConfig(skillId);
        const issues: string[] = [];
        const suggestions: string[] = [];
        
        if (!skill) {
            return {
                isCompatible: false,
                issues: ['技能配置不存在'],
                suggestions: ['请检查技能ID是否正确']
            };
        }
        
        // 检查必需字段
        if (!skill.name && !skill.reName) {
            issues.push('缺少技能名称');
            suggestions.push('添加 name 或 reName 字段');
        }
        
        if (!skill.description && !skill.desc) {
            issues.push('缺少技能描述');
            suggestions.push('添加 description 或 desc 字段');
        }
        
        if (!skill.type) {
            issues.push('缺少技能类型');
            suggestions.push('添加 type 字段 (active/passive/aura)');
        }
        
        if (!skill.effects && !skill.effect) {
            issues.push('缺少技能效果配置');
            suggestions.push('添加 effects 或 effect 字段');
        }
        
        // 检查字段一致性
        if (skill.name && skill.reName && skill.name !== skill.reName) {
            suggestions.push('name 和 reName 字段不一致，建议统一使用 name');
        }
        
        if (skill.description && skill.desc && skill.description !== skill.desc) {
            suggestions.push('description 和 desc 字段不一致，建议统一使用 description');
        }
        
        return {
            isCompatible: issues.length === 0,
            issues,
            suggestions
        };
    }
    
    /**
     * 获取技能配置统计信息
     */
    getSkillStats(): {
        totalSkills: number;
        skillsByCategory: Record<string, number>;
        skillsByType: Record<string, number>;
        skillsByQuality: Record<string, number>;
        averageMaxLevel: number;
        compatibilityScore: number;
    } {
        this.ensureInitialized();
        
        const skillsByCategory: Record<string, number> = {};
        const skillsByType: Record<string, number> = {};
        const skillsByQuality: Record<string, number> = {};
        let totalMaxLevel = 0;
        let compatibleSkills = 0;
        
        for (const skill of Array.from(this.skillConfigs.values())) {
            // 按分类统计
            const category = skill.category || skill.classType || 'unknown';
            skillsByCategory[category] = (skillsByCategory[category] || 0) + 1;
            
            // 按类型统计
            const type = skill.type || 'unknown';
            skillsByType[type] = (skillsByType[type] || 0) + 1;
            
            // 按品质统计
            const quality = skill.quality ? `质量${skill.quality}` : '未知';
            skillsByQuality[quality] = (skillsByQuality[quality] || 0) + 1;
            
            // 统计最大等级
            if (skill.maxLevel) {
                totalMaxLevel += skill.maxLevel;
            }
            
            // 统计兼容性
            const compatibility = this.validateSkillCompatibility(skill.skillId);
            if (compatibility.isCompatible) {
                compatibleSkills++;
            }
        }
        
        const totalSkills = this.skillConfigs.size;
        
        return {
            totalSkills,
            skillsByCategory,
            skillsByType,
            skillsByQuality,
            averageMaxLevel: totalSkills > 0 ? totalMaxLevel / totalSkills : 0,
            compatibilityScore: totalSkills > 0 ? (compatibleSkills / totalSkills) * 100 : 0
        };
    }
    
    /**
     * 热重载配置（开发环境）
     */
    async reload(): Promise<void> {
        console.log('🔄 Reloading configurations...');
        
        // 清除装备配置缓存
        this.equipmentTemplates.clear();
        this.equipmentsByJob.clear();
        this.equipmentsBySysType.clear();
        
        // 清除技能配置缓存
        this.skillConfigs.clear();
        this.skillTreeConfigs.clear();
        this.skillUpgradeConfigs.clear();
        this.skillEffectConfigs.clear();
        this.skillsByCategory.clear();
        this.skillsByType.clear();
        
        this.isInitialized = false;
        
        await this.initialize();
        console.log('✅ Configuration reloaded successfully');
        console.log(`📊 Equipment: ${this.equipmentTemplates.size}, Skills: ${this.skillConfigs.size}`);
    }
    
    /**
     * 确保已初始化
     */
    private ensureInitialized(): void {
        if (!this.isInitialized) {
            throw new Error('ConfigManager not initialized. Call initialize() first.');
        }
    }
}

// 导出单例实例
export const configManager = new ConfigManager();
